package com.typingtutor.dto;

import com.typingtutor.db.DatabaseManager;
import com.typingtutor.model.FieldKeyMappingRelation;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FieldKeyMappingRelationDAO {
    private static volatile FieldKeyMappingRelationDAO INSTANCE;
    private FieldKeyMappingRelationDAO() {
        // 私有构造函数，防止实例化
    }
    public static FieldKeyMappingRelationDAO getInstance() {
        if (INSTANCE == null) {
            synchronized (FieldKeyMappingRelationDAO.class) {
                if (INSTANCE == null) {
                    INSTANCE = new FieldKeyMappingRelationDAO();
                }
            }
        }
        return INSTANCE;
    }

    public List<FieldKeyMappingRelation> findByFieldMappingId(String fieldMappingId) {
        String sql = "SELECT * FROM field_key_mapping_relation WHERE field_mapping_id = ?";
        try (Connection connection = DatabaseManager.getConnection()) {
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, fieldMappingId);
            ResultSet rs = pstmt.executeQuery();
            List<FieldKeyMappingRelation> relations = new ArrayList<>();
            while (rs.next()) {
                relations.add(new FieldKeyMappingRelation(rs.getString("field_mapping_id"),
                        rs.getString("field_key_id")));
            }
            return relations;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public List<FieldKeyMappingRelation> findByFieldKeyId(String fieldKeyId) {
        String sql = "SELECT * FROM field_key_mapping_relation WHERE field_key_id = ?";
        try (Connection connection = DatabaseManager.getConnection()) {
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, fieldKeyId);
            ResultSet rs = pstmt.executeQuery();
            List<FieldKeyMappingRelation> relations = new ArrayList<>();
            while (rs.next()) {
                relations.add(new FieldKeyMappingRelation(rs.getString("field_mapping_id"),
                        rs.getString("field_key_id")));
            }
            return relations;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }
}
